package j2024.j202408;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class j0817 {
    /**
     * 1027. 最长等差数列
     * @param nums
     * @return
     */
    public int longestArithSeqLength(int[] nums) {
        int n = nums.length;
        HashMap<Integer,Integer> map = new HashMap<>();
        map.put(nums[0],0);
        int[][] dp = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                dp[i][j] = 2;
            }
        }
        int ret = 2;
        for (int i = 1; i < n; i++) {
            for (int j = i+1; j < n; j++) {
                int a = 2*nums[i]-nums[j];
                if(map.containsKey(a)){
                    dp[i][j] = dp[map.get(a)][i]+1;
                    ret =  Math.max(ret,dp[i][j]);
                }
            }
            map.put(nums[i],i);
        }
        return ret;
    }

    /**
     * 446. 等差数列划分 II - 子序列
     * @param nums
     * @return
     */
    public int numberOfArithmeticSlices(int[] nums) {
        int n = nums.length;
        int[][] dp = new int[n][n];
        HashMap<Long, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            long tmp = (long)nums[i];
            if(!map.containsKey(tmp)){
                map.put(tmp,new ArrayList<>());
            }
            map.get(tmp).add(i);

        }
        int sum = 0;
        for (int i = 2; i < n; i++) {
            for (int j = 1; j < i; j++) {
                long a = 2L *nums[j]-nums[i];
                if(map.containsKey(a)){
                    for(int k:map.get(a)){
                        if(k<j){
                            dp[j][i]+=dp[k][j]+1;
                        }else {
                            break;
                        }
                    }
                }
                sum+=dp[j][i];
            }
        }
        return sum;
    }
}
